<?php
namespace app\admin\controller;

use app\common\controller\AdminController;
use think\App;
use think\facade\Cache;
use think\facade\View;
use think\facade\Db;

class Index extends AdminController
{
    public function __construct(App $app)
    {
        parent::__construct($app);

    }
    public function index(){
        $this->app->view->engine()->layout(false);
        View::assign('grabCountMsg',$this->getGrabCount()['msg']);
        return View::fetch();
    }
    public function main(){

        //0 线索，1客户，2公海
        $cluesCount = Db::table('crm_customer')->where(['status'=> 0])->count();
        $clientCount = Db::table('crm_customer')->where(['status'=> 1])->count();
        $liberumCount = Db::table('crm_customer')->where(['status'=> 2])->count();
        // 区别管理员和业务员
        
        View::assign('cluesCount', $cluesCount);
        View::assign('clientCount', $clientCount);
        View::assign('liberumCount', $liberumCount);


        //获取本周线索 ->whereTime('at_time', 'week') 
        $cluesCount_week = Db::table('crm_customer')->where(['status'=> 0,'pr_user'=>$this->admin['username']])->count();
        //获取本月转客户数据 ->whereTime('to_kh_time', 'month') 
        $clientCount_month = Db::table('crm_customer')->where(['status'=> 1,'pr_user'=>$this->admin['username']])->count();
        //获取今年公海数据 ->whereTime('to_gh_time', 'year') 
        $liberumCount_year = Db::table('crm_customer')->where(['status'=> 2])->count();
        //成交数 TODO

        //月度排名（名）、月目标（元）、已成交（元）、完成率（%）、已成交（单）、提成点（%）， ->order('money_month DESC') ['a.`admin_id`','<>', 1],
        //管理员添加业绩设置权限。
        $prefix=config('database.connections.mysql.prefix');
        $firstday = date('Y-m-01 00:00:00');
        $lastday = date('Y-m-d 23:59:59', strtotime("$firstday +1 month -1 day"));
        $userlist=Db::query("SELECT o.*,a.admin_id,a.username,a.realname,COALESCE(a.mubiao,0) mubiao,a.ticheng FROM {$prefix}admin a LEFT JOIN (SELECT SUM(`money`) AS money_month,COUNT( `id` ) AS number_month,SUM( `return_money` ) AS return_money_month,pr_user FROM {$prefix}`crm_client_order` WHERE `status` = '审核通过' AND create_time between '{$firstday}' AND '{$lastday}' GROUP BY `pr_user` ORDER BY money_month DESC LIMIT 5) o ON a.username=o.pr_user WHERE a.admin_id<>1 AND a.is_open=1 ORDER BY o.money_month DESC LIMIT 5");
       
        //所有业务员
//        foreach ($userlist as $key => $value) {
            /*$wheretoday = [];
            $wheretoday['pr_user'] = $value['username'];
            $wheretoday['status'] = '审核通过';
            $monthOrder = Db::name('crm_client_order')->field('SUM(o.`money`) AS money_month,COUNT(o.`id`) AS number_month,SUM(o.`freight`) AS freight_month')
                            ->where($wheretoday)
                            ->whereTime('o.create_time','month')
                            ->find();*/
           
        /*    $value['money_month'] = $monthOrder['money_month']?$monthOrder['money_month']:0;
            if ($value['mubiao']>0) {
                $value['wanchenglv'] = round($monthOrder['money_month']/$value['mubiao']*100,2);
            }else{
                $value['wanchenglv']=0;
            }
            $value['number_month']=$monthOrder['number_month'];
            $value['freight_month']=$monthOrder['freight_month']?$monthOrder['freight_month']:0;
            $userlist[$key] = $value;*/
//        }
    
        // 数组排序
//        array_multisort(array_column($userlist,'money_month'),SORT_DESC,$userlist);


        //处理重新计算提成点进行重置，根据回款进行计算
        if (!empty($userlist)) {
            $setticheng = Db::name('config')->where([['name','=','admin_setticheng_config'],['inc_type','=','setticheng']])->find();
            if (!empty($setticheng['value'])) {
                $setticheng_config = json_decode($setticheng['value'],true);
            }
            foreach ($userlist as $k=>$user) {
                $temp_ticheng = 0;
                if (!empty($user['return_money_month']) && !empty($setticheng_config)) {
                    foreach ($setticheng_config as $ck => $config) {
                        if ($user['return_money_month'] >= $config['start_money']) {
                            //为空，则不限制，就近匹配
                            if (empty($config['end_money'])) {
                                $temp_ticheng = $config['num'];
                                break;
                            }

                            if ($user['return_money_month'] < $config['end_money']) {
                                $temp_ticheng = $config['num'];
                                break;
                            }
                        }
                    }
                }
                $userlist[$k]['ticheng'] = $temp_ticheng;
            }
        }

        View::assign('userlist', $userlist);

        //本人跟进动态
        //最近跟进动态  
        $result = Db::table('crm_customer')
            ->alias('c')
            ->join('crm_record r','r.customer_id = c.id')
            ->join('admin a','r.admin_id = a.admin_id')
            ->field('c.id,a.username,a.avatar,c.name,r.content,r.create_time')
            ->order('c.id desc')
            ->where(['c.pr_user'=> $this->admin['username']])
            ->limit(10)->select();
        View::assign('result', $result);


      	$strTimeToString = "000111222334455556666667";
        $strWenhou = array('夜深了，','凌晨了，','早上好！','上午好！','中午好！','下午好！','晚上好！','夜深了，');
        //echo $strWenhou[(int)$strTimeToString[(int)date('G',time())]];
        View::assign('wenhou', '尊敬的管理员'. $strWenhou[(int)$strTimeToString[(int)date('G',time())]]);
      
      

        View::assign('cluesCount_week', $cluesCount_week);
        View::assign('clientCount_month', $clientCount_month);
        View::assign('liberumCount_year', $liberumCount_year);
        // 获取待办事项
        //今日已跟进客户*个，未跟进*个，跟进率*%
        //last_up_time

        $wheretoday = [];
        $wheretoday[] = ['pr_user','=',$this->admin['username']];
        //$wheretoday['status'] = 1;
        //$wheretoday['issuccess'] = -1;
        $today_followed_count = Db::table('crm_customer')->where($wheretoday)->whereTime('last_up_time','today')->count();//今日已经跟进个数

//        not followed

        View::assign('today_followed_count', $today_followed_count);

        // 提醒列表
//        $today_tiixng = Db::table('crm_customer')->where($wheretoday)->whereTime('next_up_time','today')->select();
//        没有跟进的列表
        $today_tiixng = Db::table('crm_customer')->field('`id`,`pr_user`,`name`,`next_up_time`')->where($wheretoday)->whereNotNull('next_up_time')->where('next_up_time','<>',0)->whereTime('next_up_time','<=','tomorrow -1second')->select()->toArray();
//        待跟进数
        $not_followed_count=count($today_tiixng);
        View::assign('not_followed_count',$not_followed_count);
        $all_count=($today_followed_count+$not_followed_count);
        if ($all_count > 0) {
            $genjinlv = ($today_followed_count/$all_count)*100;
        }else{
            $genjinlv = 0;
        }
        View::assign('genjinlv', round($genjinlv,2));
        View::assign('today_tiixng', $today_tiixng);

        return $this->fetch();
    }


    public function clear(){
        Cache::clear();
        $this->success('清除缓存成功!');
       /* $R = Env::get('runtime_path');
        if ($this->_deleteDir($R)) {
            $this->success('清除缓存成功!');
        } else {
            $this->error('清除缓存失败!');
        }*/
    }
    private function _deleteDir($R)
    {
        $handle = opendir($R);
        while (($item = readdir($handle)) !== false) {
            if ($item != '.' and $item != '..') {
                if (is_dir($R . '/' . $item)) {
                    $this->_deleteDir($R . '/' . $item);
                } else {
                    if (!unlink($R . '/' . $item))
                        die('error!');
                }
            }
        }
        closedir($handle);
        return rmdir($R);
    }

    //退出登陆
    public function logout(){
        session(null);
        session('referer',$_SERVER["HTTP_REFERER"]);
        $this->redirect(myurl('login/index'));
    }
    
}
